layui.use(['form','layer','table','laytpl','upload'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        upload = layui.upload,
        table = layui.table;
    
    //上传
    var uploadInst = upload.render({
      elem: '#upload' //绑定元素
      ,url: '../product/userFileUpload/' //上传接口
      ,method: 'post'
      ,accept : "file"
	  ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
		  layer.load(); //上传loading
	  }
      ,done: function(res, index, upload){
    	layer.closeAll('loading'); //关闭loading
        //上传完毕回调
    	layer.msg('上传成功');
      }
      ,error: function(){
        //请求异常回调
      }
    });
    
    //用户列表
    var tableIns = table.render({
        elem: '#userList',
        method: 'post',
        url : '../user/dataGrid',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 20,
        initSort: {
            field: 'createTime' //排序字段，对应 cols 设定的各字段名
            ,type: 'asc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        id : "userListTable",
        cols : [[
        	{field: 'employeeId', title: '工号', minWidth:100, align:"center"},
            {field: 'loginName', title: '用户名', minWidth:100, align:"center"},
            {field: 'name', title: '姓名', minWidth:100, align:"center"},
            {field: 'organizationName', title: '渠道', minWidth:100, align:"center"},
            {field: 'createTime', title: '创建时间', minWidth:150, align:"center"},
            {field: 'sex', minWidth:50, title: '用户性别', align:'center',templet:function(d){
            	return d.sex == "0" ? "男" : "女";
            }},
            {field: 'age', minWidth:50, title: '年龄', align:'center'},
            {field: 'phone', title: '电话', align:'center'},
            {field: 'rolesList', title: '角色', align:'center'},
            {field: 'userType', title: '用户类型', align:'center',templet:function(d){
                if(d.userType == "0"){
                    return "管理员";
                }else if(d.userType == "1"){
                    return "用户";
                }else{
                    return "未知类型";
                }
            }},
            {field: 'status', title: '用户状态',  align:'center',templet:function(d){
            	return d.status == "0" ? "正常使用" : "限制使用";
            }},
            {title: '操作', minWidth:175, templet:'#userListBar',fixed:"right",align:"center"}
        ]]
    });

    //搜索
    $(".search_btn").on("click",function(){
    	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
        if($(".searchVal").val() != ''){
        	setTimeout(function(){
        		table.reload("userListTable",{
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    where: {
                    	name: $(".searchVal").val()  //搜索的关键字
                    }
                });
    			layer.close(index);
    		},2000);
        }else{
            //layer.msg("请输入搜索的内容");
        	tableIns.reload();
        	layer.close(index);
        }
    });

    //添加用户
    function addUser(){
        var index = layer.open({
            title : "添加用户",
            type : 2,
            //area: ['500px', '500px'],
            content : "../user/addPage",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    //编辑用户
    function editUser(edit){
        var index = layui.layer.open({
            title : "编辑用户",
            type : 2,
            content : "../user/editPage?id=" + edit.id,
            success : function(layero, index){
            	//alert(JSON.stringify(edit));
                var body = layui.layer.getChildFrame('body', index);
                body.find(".sex").val(edit.sex);  //性别
                body.find(".userType").val(edit.userType);  //用户类型
                body.find(".status").val(edit.status);  //用户状态
                //body.find(".roleIds").val(edit.rolesList);  //角色
                form.render();
                setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    $(".addNews_btn").click(function(){
        addUser();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
        	editUser(data);
        }else if(layEvent === 'del'){ //删除
        	var id = data.id;
            layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
    			$.ajax({
      			type : "POST",
      			url : "../user/delete",
      			data : {
      				"id" : id
      			},
      			success : function() {
      				top.layer.msg("用户删除成功！");
      	 			tableIns.reload();
                    layer.close(index);
      			}
    			});
            });
        }
    });
})
